using System;
using K4os.Compression.LZ4;

namespace PvpServer
{
    public class Lz4Helper
    {
       
	public static byte[] CompressWithLength(byte[] data)
	{
		if (data == null || data.Length == 0)
			return new byte[0];

		// 计算压缩后可能的最大大小
		int maxCompressedLength = LZ4Codec.MaximumOutputSize(data.Length);
		byte[] compressedBuffer = new byte[maxCompressedLength];
		
		// 压缩数据
		int compressedSize = LZ4Codec.Encode(
			data, 0, data.Length,
			compressedBuffer, 0, compressedBuffer.Length,
			LZ4Level.L00_FAST
		);
		
		// 创建包含原始长度的结果数组
		byte[] result = new byte[compressedSize + 4];
		
		// 将原始长度存储在前4个字节
		BitConverter.GetBytes(data.Length).CopyTo(result, 0);
		
		// 复制压缩后的数据
		Buffer.BlockCopy(compressedBuffer, 0, result, 4, compressedSize);
		
		return result;
	}

	public static byte[] DecompressWithLength(byte[] compressed)
	{
		if (compressed == null || compressed.Length <= 4)
			return new byte[0];

		// 从前4个字节读取原始长度
		int originalSize = BitConverter.ToInt32(compressed, 0);
		
		// 创建结果数组
		byte[] result = new byte[originalSize];
		
		// 解压缩数据
		LZ4Codec.Decode(
			compressed, 4, compressed.Length - 4,
			result, 0, result.Length
		);
		
		return result;
	}

    }
}